<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="filelist"
      :class="{disable:filelist.length>0}"
      :http-request="httpRequset"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="isShowprogress" :text-inside="true" :stroke-width="26" :percentage="percentage" style="width:146px" />
    <el-dialog title="预览" :visible="isShowdialog" @close="isShowdialog = false">
      <el-row type="flex" justify="center">
        <img :src="imgSrc" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({ SecretId: 'AKIDQggQt64lBMGtFK9hyyh9KErBF2YnmUv6', SecretKey: 'vZv0pNeeOr3xc06vTkkTv60dz4sPfeMo' })
console.log(cos)
export default {
  data() {
    return {
      filelist: [],
      isShowdialog: false,
      imgSrc: '',
      isShowprogress: false,
      percentage: 0
    }
  },
  methods: {
    httpRequset(params) {
      this.isShowprogress = true
      cos.putObject({
        Bucket: 'hrproject-1309020758', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        if (!err) {
          this.filelist[0].status = 'success'
          this.filelist[0].url = 'http://' + data.Location
        }
        setTimeout(() => {
          this.isShowprogress = false
        }, 1000)
      })
    },
    onPreview(file, filelist) {
      this.isShowdialog = true
      this.imgSrc = file.url
    },
    onRemove(file, filelist) {
      this.filelist = filelist
    },
    onChange(file, filelist) {
      this.filelist = filelist
    },
    beforeUpload(file) {
      console.log(file)
      const mixsize = 2 * 1024 * 1024
      if (file.size > mixsize) {
        this.$message.warning('文件不能大于2m')
        return false
      }
      const whiteList = ['image/jpeg', 'image/png']
      if (!whiteList.includes(file.type)) {
        this.$message.warning('只能上传png和jpeg文件')
        return false
      }
    }

  }

}
</script>

<style lang="scss" scoped>
.disable {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
img{
  object-fit: contain;
}
</style>
